package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingHrvInfo;
import com.ruoyi.ring.domain.dto.RingHrvInfoAddDTO;
import com.ruoyi.ring.domain.dto.RingHrvInfoDTO;
import com.ruoyi.ring.domain.vo.RingHrvInfoVO;
import com.ruoyi.ring.service.IRingHrvInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 心率变异性历史心率 （APP）
 */
@Slf4j
@RestController
@RequestMapping("/ring/app/ring_hrv_Info")
public class AppHrvInfoController extends BaseController
{
    @Resource
    private IRingHrvInfoService ringHrvInfoService;

    /**
     * 上报变异性历史心率信息-app
     */
    @Log(title = "变异性历史心率信息", businessType = BusinessType.INSERT)
    @PostMapping("/add-ring_hrv-info")
    public AjaxResult addRingHrvInfo(@RequestBody RingHrvInfoAddDTO addDTO)
    {
        String deviceSn = addDTO.getDeviceSn();
        try {
            List<RingHrvInfoAddDTO.StressDTO> stressDTOList = addDTO.getStress();
            stressDTOList.forEach(stressDTO -> {
                Date dailyValue = stressDTO.getDailyValue();
                RingHrvInfo hrvInfo = ringHrvInfoService.selectOneRingHrvInfo(Builder.of(RingHrvInfo::new).
                        with(RingHrvInfo::setDeviceSn, deviceSn).
                        with(RingHrvInfo::setDailyValue, dailyValue).build());
                RingHrvInfo ringHrvInfo = Convert.convert(RingHrvInfo.class,stressDTO);
                if(hrvInfo != null){
                    ringHrvInfo.setId(hrvInfo.getId());
                    ringHrvInfo.setDeviceSn(deviceSn);
                    ringHrvInfoService.updateRingHrvInfo(ringHrvInfo);
                }else {
                    ringHrvInfo.setDeviceSn(deviceSn);
                    ringHrvInfoService.insertRingHrvInfo(ringHrvInfo);
                }
            });

            return AjaxResult.success();
        }catch (Exception e){
            throw new RuntimeException("上报变异性历史心率信息失败！");
        }
    }

    /**
     * 变异性历史心率信息列表-app
     */
    @GetMapping("/query-ring_hrv-info")
    public AjaxResult queryRingHrvInfo(RingHrvInfoDTO ringHrvInfoDTO)
    {
        long userId = SecurityUtils.getUserId();
        log.info("变异性历史心率信息列表queryRingHrvInfo: userId={}, param={}", userId, JSON.toJSONString(ringHrvInfoDTO));
        RingHrvInfoVO ringHrvInfoVO = ringHrvInfoService.queryRingHrvInfo(ringHrvInfoDTO);
        return AjaxResult.success(ringHrvInfoVO);
    }
}
